package job_center

import (
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	dto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/job_center"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/job_center"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type JobCenterController struct {
	controller.BaseController
	jobCenterService job_center.JobCenterServiceIface
}

func NewJobCenterController(
	jobCenterService job_center.JobCenterServiceIface,
) *JobCenterController {
	return &JobCenterController{
		jobCenterService: jobCenterService,
	}
}

// RegisterRouter
// 注册路由
func (c *JobCenterController) RegisterRouter(g *gin.RouterGroup) {
	//我的任务列表
	g.GET("job/my-list", c.myList)
	//任务重试
	g.POST("job/rerun", c.rerun)
	//任务完成通知
	g.GET("job/finished-notice", c.notice)
}

func (c *JobCenterController) myList(ctx *gin.Context) {
	req := dto.MyListRequest{}
	if err := ctx.ShouldBind(&req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(req, err))
		return
	}
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 20
	}

	resp, err := c.jobCenterService.GetMyJobList(ctx, &req)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetMyJobList request:%#v, err:%s", req, err.Error())
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, resp)
}

func (c *JobCenterController) rerun(ctx *gin.Context) {
	req := dto.RerunJobRequest{}
	if err := ctx.ShouldBind(&req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(req, err))
		return
	}
	err := c.jobCenterService.RerunJob(ctx, &req)
	if err != nil {
		stark.Logger.Errorf(ctx, "RerunJob request:%#v, err:%s", req, err.Error())
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, map[string]interface{}{"id": req.Id})
}

func (c *JobCenterController) notice(ctx *gin.Context) {
	resp, err := c.jobCenterService.FinishedJobNotice(ctx)
	if err != nil {
		stark.Logger.Errorf(ctx, "notice request:%#v, err:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	c.Success(ctx, resp)
}
